from pml.Parser.public import *

class Function(Node):
    def __init__(self, id=None, args=None, body=None, bp=None, ep=None, depth=0):
        super().__init__('function-common', bp, ep, depth)
        self.id = id
        self.args = args
        self.body = body
    def __repr__(self):
        depth = '\t' * self.depth
        return 'Function({})(\n{}args={},\n{}body={}\n{})'.format(self.depth, depth, self.args, depth, self.body, '\t' * (self.depth - 1))

    def getObject(self):
        self.methods['__init__'] = self.tp_init

        return self

    @staticmethod
    def tp_init(frame, this, position):
        pass

class FunctionBuilder(ASTBuilder):
    def __init__(self, tokens=None, depth=0):
        super().__init__('Function', tokens, depth)

    def getObject(self):
        self.methods['__init__'] = self.tp_init

        self.methods['buildFunction'] = self.buildFunction

        return self

    @staticmethod
    def buildFunction(frame, this: 'FunctionBuilder', position):
        bp = this.token.bp
        this.getNextToken()
        if this.token.type == TokenConstants.TT_SIGN and this.token.value == TokenConstants.TV_LP1:
            pass
        if this.token.type != TokenConstants.TT_NAME:
            # error
            pass
        name = Objects.object.PMTypeObject(Name(this.token.value, this.token.bp, this.token.ep).getObject())
        this.getNextToken()
        if this.token.type != TokenConstants.TT_SIGN or this.token.value != TokenConstants.TV_LP1:
            # error
            pass
        args = []
        this.getNextToken()
        while this.token.type != TokenConstants.TT_SIGN and this.token.value != TokenConstants.TV_RP1:
            if this.token.type != TokenConstants.TT_NAME:
                # error
                pass
            args.append(Objects.object.PMTypeObject(Name(this.token.value, this.token.bp, this.token.ep).getObject()))
            this.getNextToken()
            if this.token.type == TokenConstants.TT_SIGN and this.token.value == TokenConstants.TV_RP1:
                break
            if this.token.type != TokenConstants.TT_SIGN or this.token.value != TokenConstants.TV_COMMA:
                # error
                pass
            this.getNextToken()
        this.getNextToken()
        if this.token.type != TokenConstants.TT_KEYWORD or this.token.value != TokenConstants.Keywords.BEGIN:
            # error
            pass
        this.getNextToken()
        bodyBuilder = Parser.ASTBuilder(this.tokens, depth=this.depth + 1)
        body = bodyBuilder.buildAST(frame, bodyBuilder, position)
        ep = this.token.ep
        try:
            this.getNextToken()
        except StopIteration:
            pass
        return Objects.object.PMTypeObject(Function(name, args, body, bp, ep, depth=this.depth).getObject())


    @staticmethod
    def tp_init(frame, this, position):
        pass
